package com.doghome.mysb.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestControllerAdvice
public class GlobalExceptionHandler {

	public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/**
	 * 处理异常，将异常获取后封装成AjaxResult对象返回到前端
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = {RuntimeException.class})
	public void ExceptionHandler(RuntimeException e,HttpServletResponse response) {
		log.error(e.getMessage(), e);
		ObjectMapper objectMapper = new ObjectMapper();
		response.setStatus(500);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		try {
			response.getWriter().write(objectMapper.writeValueAsString(AjaxResult.error(5001, e.getMessage())));
			response.getWriter().flush();
			response.getWriter().close();
		} catch (JsonProcessingException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
